import 'package:fluent_ui/fluent_ui.dart';
import 'package:fnos_tv_desktop/view/main/category/category_view.dart';
import 'package:fnos_tv_desktop/view/main/media_db/media_db_view.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

import '../../core/model/media_databases.dart';
import 'favor/favor_view.dart';
import 'home/home_view.dart';
import '../../application/application.dart';
import 'common/title_bar_actions.dart';
import 'main_page_model.dart';

class MainPage extends StatefulWidget {
  const MainPage({super.key});

  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> with RouteAware {
  final model = MainPageModel();

  @override
  void initState() {
    model.init(context);
    super.initState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final route = ModalRoute.of(context) as PageRoute<dynamic>;
    Application.routeObserver.subscribe(this, route);
  }

  @override
  void dispose() {
    model.dispose();
    Application.routeObserver.unsubscribe(this);
    super.dispose();
  }

  @override
  void didPush() {
    model.refresh();
  }

  @override
  void didPopNext() {
    //model.refresh();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: model.items,
      builder: (context, asyncSnapshot) {
        if (asyncSnapshot.hasError) {
          return Center(child: Text('加载失败: ${asyncSnapshot.error}'));
        }
        if (asyncSnapshot.connectionState != ConnectionState.active) {
          return const Center(child: ProgressRing());
        }
        final items = asyncSnapshot.data as List<NavigationPaneItem>;
        return StreamBuilder(
          stream: model.selectedIndexStream,
          builder: (context, asyncSnapshot) {
            final index = asyncSnapshot.data ?? 0;
            return Provider.value(
              value: model,
              builder: (context, child) {
                return NavigationPaneTheme(
                  data: NavigationPaneThemeData(
                    selectedIconColor: WidgetStatePropertyAll(
                      FluentTheme.of(context).accentColor,
                    ),
                    unselectedTextStyle: WidgetStatePropertyAll(
                      TextStyle(
                        fontSize: 14,
                        color: FluentTheme.of(context).activeColor,
                        fontWeight: FontWeight.normal,
                      ),
                    ),
                    selectedTextStyle: WidgetStatePropertyAll(
                      TextStyle(
                        fontSize: 16,
                        color: FluentTheme.of(context).accentColor,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  child: NavigationView(
                    pane: NavigationPane(
                      displayMode: PaneDisplayMode.auto,
                      header: Padding(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 12.0,
                          vertical: 12,
                        ),
                        child: Image.asset('images/logo_h.png', height: 35),
                      ),
                      items: items,
                      selected: index,
                      onChanged: (index) {
                        setState(() {
                          model.selectedIndex = index;
                        });
                      },
                    ),
                    paneBodyBuilder: (item, child) {
                      return Navigator(
                        key: model.navigatorKey,
                        initialRoute: '/',
                        onGenerateRoute: (settings) {
                          Widget child;
                          switch (settings.name) {
                            case '/':
                              child = HomeView(key: ValueKey('home'));
                              break;
                            case '/favor':
                              child = FavorView(key: ValueKey('favor'));
                              break;
                            case '/media_db':
                              final db = settings.arguments as MediaDatabase;
                              final key = ObjectKey(db);
                              child = MediaDbView(key: key, db: db);
                              break;
                            case '/category':
                              final category = settings.arguments as String;
                              final key = ValueKey(category);
                              child = CategoryView(
                                key: key,
                                category: category,
                              );
                              break;
                            default:
                              child = Container();
                              break;
                          }
                          return FluentPageRoute(
                            builder: (context) {
                              return child;
                            },
                          );
                        },
                      );
                    },
                  ),
                );
              },
            );
          },
        );
      },
    );
  }
}
